package ua.com.globallogic.basecamp.krasnyanskiy.anagrams.ioutils;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;

public class FileValidator {
    public boolean validate(File file) throws FileValidationException, IOException {
        if (file == null)
            throw new FileValidationException("Value cannot be null");

        if (!file.isFile())
            throw new FileValidationException("No such file");

        if (!file.getName().endsWith((".txt")))
            throw new FileValidationException("Not a text file");

        // 104857600 = 100 M
        if (file.length() <= 0 && file.length() > 104857600)
            throw new FileValidationException("Not a proper size of file");

        // check UTF8 encoding
        try {
            Charset.availableCharsets().
                    get("UTF-8").
                    newDecoder().
                    decode(ByteBuffer.
                            wrap(FileUtils.
                                    readFileToByteArray(file)));
        } catch (CharacterCodingException e) {
            throw new FileValidationException("Incompatible character encodings: non UTF-8");
        }

        return true;
    }
}
